package com.example.tenmins;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.TimeZone;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.SeekBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class Setting_alarm extends Activity {

	public static Boolean ISNEW = false;
	public static int POSITION = 0;
	public static int ID ;
	
	private static final String INTENT_ACTION = "com.example.tenmins";

	// �쒓컙
	int hour, minute;
	TextView hour_t, minute_t, am_pm_t;
	TextView hour_plus, hour_minus, minute_plus, minute_minus;

	// �붿씪
	ImageView mon, tue, wed, thu, fri, sat, sun;
	boolean checked_mon, checked_tue, checked_wed, checked_thu, checked_fri,
			checked_sat, checked_sun;

	// �뚮엺��
	ArrayList<String> musicList;
	ArrayAdapter<String> musicAdapter;
	RadioGroup sound;
	RadioButton radio_btn;
	TextView musicTitle;
	String title;
	String music_id;
	

	private SharedPreferences sharedPref;
	private SharedPreferences.Editor sharedEditor;
	

	SeekBar volume;
	int volume_control;


	Spinner spin;
	ArrayList<Alarm_data> data ; 
	ArrayAdapter<?> adapter;
	String game;
	ImageButton complete;

	static Context context;
	Calendar cal = Calendar.getInstance();
	//GregorianCalendar currentCalendar = new GregorianCalendar(TimeZone.getTimeZone("GMT+09:00"));
	GregorianCalendar currentCalendar = (GregorianCalendar) Calendar.getInstance(TimeZone.getTimeZone("GMT+09:00"));
	AlarmManager alarmManager;
	
	// ��옣
	Button save;
	Database db;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.setting_alarm);

		context = getApplicationContext();
		
		sharedPref = getPreferences(Context.MODE_PRIVATE);
    	sharedEditor = sharedPref.edit();
    	 
    	data = MainActivity.data;
		
		db = new Database(this);
		db.open();

		hour_t = (TextView) findViewById(R.id.hour);
		minute_t = (TextView) findViewById(R.id.min);
		am_pm_t = (TextView) findViewById(R.id.AM);

		long time = System.currentTimeMillis();
		Calendar c = Calendar.getInstance();
		c.setTimeInMillis(time);

		mon = (ImageView) findViewById(R.id.mon);
		tue = (ImageView) findViewById(R.id.tue);
		wed = (ImageView) findViewById(R.id.wed);
		thu = (ImageView) findViewById(R.id.thu);
		fri = (ImageView) findViewById(R.id.fri);
		sat = (ImageView) findViewById(R.id.sat);
		sun = (ImageView) findViewById(R.id.sun);

		radio_btn = (RadioButton)findViewById(R.id.radio0);
		musicTitle = (TextView)findViewById(R.id.musicTitle);
		musicTitle.setOnClickListener(musicTitleListener);
		
		spin = (Spinner) findViewById(R.id.spinner1);
		adapter = ArrayAdapter.createFromResource(this, R.array.method,
				android.R.layout.simple_spinner_item);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spin.setAdapter(adapter);
		spin.setOnItemSelectedListener(gameListener);
		game = "";

		volume = (SeekBar) findViewById(R.id.seekBar1);
		volume.setOnSeekBarChangeListener(volumeListener);
		volume.setMax(100);
		volume.incrementProgressBy(1);
		
		if (ISNEW == true) {

			hour = c.get(Calendar.HOUR_OF_DAY);
			minute = c.get(Calendar.MINUTE);

			if (c.get(Calendar.AM_PM)==Calendar.AM) {
				
				am_pm_t.setText("AM");
			}else{
				if(hour == 12)
					;
				else
					hour = hour - 12;
				am_pm_t.setText("PM");
			}
				

			if (hour < 10)
				hour_t.setText("0" + Integer.toString(hour));
			else
				hour_t.setText(Integer.toString(hour));

			if (minute < 10)
				minute_t.setText("0" + Integer.toString(minute));
			else
				minute_t.setText(Integer.toString(minute));
			
			ID = db.getLastId()+1;
			
			
			checked_mon = false;
			checked_tue = false;
			checked_wed = false;
			checked_thu = false;
			checked_fri = false;
			checked_sat = false;
			checked_sun = false;
			
			alarmManager = (AlarmManager)getApplicationContext().getSystemService(Context.ALARM_SERVICE);
	    	 alarmManager.setTimeZone("GMT+09:00");
		}

		else {
			
			
			Alarm_data selectedAlarm = MainActivity.data.get(POSITION);
			
			//String hour_minute = selectedAlarm.getTime();
			//Scanner scan = new Scanner(hour_minute);
			//scan.useDelimiter("시");
			
			ID = selectedAlarm.getId();
			
			/*String h = scan.next();
			if(Integer.parseInt(h) < 10)
				h = "0" + h;
			String m = scan.next();
			if(m.length() == 3){
				m = m.substring(1, 2);
				m = "0" + m;
			}
			else if(m.length() == 4)
				m = m.substring(1, 3);*/
			
			int t_h = db.getHour(ID);
			int t_m = db.getMin(ID);
			
			String h = "";
			String m = "";
			
			if(t_h < 10)
				h = "0" + t_h;
			else
				h = "" + t_h;
			
			if(t_m < 10)
				m = "0" + t_m;
			else
				m = "" + t_m;
			
			
			hour_t.setText(h);
			minute_t.setText(m);
			am_pm_t.setText(selectedAlarm.getAm_Pm());
			

			if(selectedAlarm.getDay_mon() == R.drawable.monday_checked + 2)
				mon.setImageResource(R.drawable.monday_checked);
			else
				mon.setImageResource(R.drawable.monday);
			if(selectedAlarm.getDay_tue() == R.drawable.tuesday_checked + 2)
				tue.setImageResource(R.drawable.tuesday_checked);
			else
				tue.setImageResource(R.drawable.tuesday);
			

			if(selectedAlarm.getDay_wed() == R.drawable.wednesday_checked + 2)
				wed.setImageResource(R.drawable.wednesday_checked);
			else
				wed.setImageResource(R.drawable.wednesday);
			

			if(selectedAlarm.getDay_thu() == R.drawable.thursday_checked + 2)
				thu.setImageResource(R.drawable.thursday_checked);
			else
				thu.setImageResource(R.drawable.thursday);
			

			if(selectedAlarm.getDay_fri() == R.drawable.friday_checked + 2)
				fri.setImageResource(R.drawable.friday_checked);
			else
				fri.setImageResource(R.drawable.friday);
			

			if(selectedAlarm.getDay_sat() == R.drawable.saturday_checked + 2)
				sat.setImageResource(R.drawable.saturday_checked);
			else
				sat.setImageResource(R.drawable.saturday);
			

			if(selectedAlarm.getDay_sun() == R.drawable.sunday_checked + 2)
				sun.setImageResource(R.drawable.sunday_checked);
			else
				sun.setImageResource(R.drawable.sunday);
			
			checked_mon = db.isCheckedMon(ID);
			checked_tue = db.isCheckedTue(ID);
			checked_wed = db.isCheckedWed(ID);
			checked_thu = db.isCheckedThu(ID);
			checked_fri = db.isCheckedFri(ID);
			checked_sat = db.isCheckedSat(ID);
			checked_sun = db.isCheckedSun(ID);
			
			musicTitle.setText(db.getMusicTitle(ID));
			volume.setProgress(db.getVolume(ID));
			spin.setSelection(db.getGame(ID));
		}

		hour_plus = (TextView) findViewById(R.id.hour_plus);
		hour_minus = (TextView) findViewById(R.id.hour_minus);
		minute_plus = (TextView) findViewById(R.id.minute_plus);
		minute_minus = (TextView) findViewById(R.id.minute_minus);

		hour_plus.setOnClickListener(buttonListener);
		hour_minus.setOnClickListener(buttonListener);
		minute_plus.setOnClickListener(buttonListener);
		minute_minus.setOnClickListener(buttonListener);
		am_pm_t.setOnClickListener(buttonListener);

		mon.setOnClickListener(dayListener);
		tue.setOnClickListener(dayListener);
		wed.setOnClickListener(dayListener);
		thu.setOnClickListener(dayListener);
		fri.setOnClickListener(dayListener);
		sat.setOnClickListener(dayListener);
		sun.setOnClickListener(dayListener);

		sound = (RadioGroup) findViewById(R.id.radioGroup1);
		sound.setOnCheckedChangeListener(soundListener);

		title = musicTitle.getText().toString();

		musicList = new ArrayList<String>();
		musicList = getMusicList();
		musicAdapter = new ArrayAdapter<String>(this,
					android.R.layout.simple_list_item_single_choice, musicList);

		save = (Button) findViewById(R.id.save);
		save.setOnClickListener(saveListener);
		
		db.close();
		
	}

	Button.OnClickListener saveListener = new Button.OnClickListener() {
		int h = 0, m = 0, vc = 0;
		String ap = "", g = "", s = "";
		int check_mon = 0, 
			check_tue = 0,
			check_wed = 0, 
			check_thu = 0,
			check_fri = 0, 
			check_sat = 0, 
			check_sun = 0;
		
		int reqCode = ID ; 
		
		@Override
		public void onClick(View arg0) {
			
	
			if (checked_mon)
				check_mon = 1;
			if (checked_tue)
				check_tue = 1;
			if (checked_wed)
				check_wed = 1;
			if (checked_thu)
				check_thu = 1;
			if (checked_fri)
				check_fri = 1;
			if (checked_sat)
				check_sat = 1;
			if (checked_sun)
				check_sun = 1;
			
			
			h = Integer.parseInt(hour_t.getText().toString());
			//if(am_pm_t.getText().equals("PM"))
			//	h = h + 12;
			m = Integer.parseInt(minute_t.getText().toString());
			ap = am_pm_t.getText().toString();
			g = game;
			s = title;
			vc = volume_control;
			
		
			
			if((check_mon+check_tue+check_tue+check_wed+check_thu+check_fri+check_sat+check_sun)==0){
				Toast.makeText(context, "요일을 선택하세요", Toast.LENGTH_SHORT).show();
				return;
			}
			
			/*if(sound.getCheckedRadioButtonId()==-1){
				Toast.makeText(context, "알람음을 선택하세요", Toast.LENGTH_SHORT).show();
				return;
			}*/
			
			if(musicTitle.getText().toString().equals("")){
				Toast.makeText(context, "알람음을 선택하세요", Toast.LENGTH_SHORT).show();
				return;
			}
			
			getData();
			
			
			int hh = Integer.parseInt(hour_t.getText().toString());
			int mm = Integer.parseInt(minute_t.getText().toString());
			String ampm = am_pm_t.getText().toString();
			

			GregorianCalendar gregorianCalendar = new GregorianCalendar(TimeZone.getTimeZone("GMT+09:00"));
				
		    int reqCode = ID;
		    
			Intent intent = new Intent(context, PopupActivity.class);
			intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		    //Intent intent = new Intent(I);
			intent.putExtra("reqCode", reqCode);
			
			
			gregorianCalendar.set(Calendar.HOUR, hh);
			gregorianCalendar.set(Calendar.MINUTE, mm);
			if(ampm.equals("am"))
				gregorianCalendar.set(Calendar.AM_PM, Calendar.AM);
			else
				gregorianCalendar.set(Calendar.AM_PM, Calendar.PM);
			gregorianCalendar.set(Calendar.SECOND, 0);
			
			//Log.i("TAG",gregorianCalendar.getTimeInMillis()+":");
			reqCode = ID;

			//intent.putExtra("reqCode", reqCode);
			//intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			//Log.i("id", "id:"+reqCode);
			//intent.putExtra("reqCode", reqCode+gregorianCalendar.getTimeInMillis()+"/"+cal.getTimeInMillis());
			
			PendingIntent pi = PendingIntent.getActivity(Setting_alarm.this, reqCode, intent,PendingIntent.FLAG_UPDATE_CURRENT);
			
			alarmManager = (AlarmManager)getApplicationContext().getSystemService(Context.ALARM_SERVICE);
			alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, gregorianCalendar.getTimeInMillis(),AlarmManager.INTERVAL_DAY, pi);
			
			finish();
			
		}
		
		
		public void getData(){
			
			Database db = new Database(getApplicationContext());
			db.open();

			if(ISNEW == true){
				db.addAlarmList(h, m, ap, check_mon, check_tue, check_wed, 
						check_thu, check_fri, check_sat, check_sun, g, s, vc);
				
				ID = db.getLastId();
				
				int index = musicList.indexOf(s);
				music_id = getMusicID(index);
				db.addMusicList(music_id);
				
				int mon_image = R.drawable.monday_list, 
				    	tue_image = R.drawable.tuesday_list, 
				    	wed_image = R.drawable.wednesday_list, 
				    	thu_image = R.drawable.thursday_list, 
				    	fri_image = R.drawable.friday_list, 
				    	sat_image = R.drawable.saturday_list, 
				    	sun_image = R.drawable.sunday_list;
				
				if(check_mon == 1)	mon_image = R.drawable.monday_list_checked;
				
				if(check_tue == 1)	tue_image = R.drawable.tuesday_list_checked;
				
				if(check_wed == 1)	wed_image = R.drawable.wednesday_list_checked;
				
				if(check_thu == 1)	thu_image = R.drawable.thursday_list_checked;
				
				if(check_fri == 1)	fri_image = R.drawable.friday_list_checked;
				
				if(check_sat == 1)	sat_image = R.drawable.saturday_list_checked;
				
				if(check_sun == 1)	sun_image = R.drawable.sunday_list_checked;
				
				Alarm_data newAlarm = new Alarm_data(R.drawable.alarm, h + "시" + m + " 분", mon_image, tue_image, wed_image, 
						thu_image, fri_image, sat_image, sun_image, ap, ID);
				
				data.add(newAlarm);				
				//MainActivity.data.add(newAlarm);
				//MainActivity.adapter.notifyDataSetChanged();

				
			}else{
				
				int mon_image = R.drawable.monday_list, 
			    	tue_image = R.drawable.tuesday_list, 
			    	wed_image = R.drawable.wednesday_list, 
			    	thu_image = R.drawable.thursday_list, 
			    	fri_image = R.drawable.friday_list, 
			    	sat_image = R.drawable.saturday_list, 
			    	sun_image = R.drawable.sunday_list;
				
				db.updateAlarmList(h, m, ap, check_mon, check_tue, check_wed, 
						check_thu, check_fri, check_sat, check_sun, g, s, vc, ID);
				
				if(check_mon == 1)	mon_image = R.drawable.monday_list_checked;
				
				if(check_tue == 1)	tue_image = R.drawable.tuesday_list_checked;
				
				if(check_wed == 1)	wed_image = R.drawable.wednesday_list_checked;
				
				if(check_thu == 1)	thu_image = R.drawable.thursday_list_checked;
				
				if(check_fri == 1)	fri_image = R.drawable.friday_list_checked;
				
				if(check_sat == 1)	sat_image = R.drawable.saturday_list_checked;
				
				if(check_sun == 1)	sun_image = R.drawable.sunday_list_checked;
					
				Alarm_data newAlarm = new Alarm_data(R.drawable.alarm, h + "시" + m + " 분", mon_image, tue_image, wed_image, 
						thu_image, fri_image, sat_image, sun_image, ap, ID);
				
				int index = musicList.indexOf(s);
				music_id = getMusicID(index);
				
				data.remove(POSITION);
				data.add(POSITION, newAlarm);
				db.updateMusicList(music_id, ID);
			}
			
			db.close();
		}

	
	};
	
	

	Spinner.OnItemSelectedListener gameListener = new Spinner.OnItemSelectedListener() {

		@Override
		public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			// TODO Auto-generated method stub
			game = spin.getSelectedItem().toString();
		}

		@Override
		public void onNothingSelected(AdapterView<?> arg0) {
			// TODO Auto-generated method stub

		}

	};

	public ArrayList<String> getMusicList() {
		ArrayList<String> list = new ArrayList<String>();
		String[] proj = {
				MediaStore.Audio.Media.TITLE };

		Cursor cursor = managedQuery(
				MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, proj, null, null,
				null);

		if (cursor != null && cursor.moveToFirst()) {
			String title;
			
			int musicTitleCol = cursor
					.getColumnIndex(MediaStore.Audio.Media.TITLE);
			do {
				title = cursor.getString(musicTitleCol);
				list.add(title);
			} while (cursor.moveToNext());
		}
		//cursor.close();
		return list;
	}

	public String getMusicID(int index){
		ArrayList<String> list = new ArrayList<String>();
		String[] proj = {
				MediaStore.Audio.Media._ID };

		Cursor cursor = managedQuery(
				MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, proj, null, null,
				null);

		if (cursor != null && cursor.moveToFirst()) {
			String musicID;
			
			int musicIDCol = cursor.getColumnIndex(MediaStore.Audio.Media._ID);
			do {
				musicID = cursor.getString(musicIDCol);
				list.add(musicID);
			} while (cursor.moveToNext());
		}
		//cursor.close();
		return list.get(index);
	}
	
	SeekBar.OnSeekBarChangeListener volumeListener = new SeekBar.OnSeekBarChangeListener() {

		@Override
		public void onStopTrackingTouch(SeekBar seekBar) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onStartTrackingTouch(SeekBar seekBar) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onProgressChanged(SeekBar seekBar, int progress,
				boolean fromUser) {
			// TODO Auto-generated method stub
			volume_control = progress;
		}
	};

	ImageView.OnClickListener dayListener = new ImageView.OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			switch (v.getId()) {
			case R.id.mon:
				if (!checked_mon) {
					mon.setImageResource(R.drawable.monday_checked);
					checked_mon = true;
				} else {
					mon.setImageResource(R.drawable.monday);
					checked_mon = false;
				}
				break;
			case R.id.tue:
				if (!checked_tue) {
					tue.setImageResource(R.drawable.tuesday_checked);
					checked_tue = true;
				} else {
					tue.setImageResource(R.drawable.tuesday);
					checked_tue = false;
				}
				break;
			case R.id.wed:
				if (!checked_wed) {
					wed.setImageResource(R.drawable.wednesday_checked);
					checked_wed = true;
				} else {
					wed.setImageResource(R.drawable.wednesday);
					checked_wed = false;
				}
				break;
			case R.id.thu:
				if (!checked_thu) {
					thu.setImageResource(R.drawable.thursday_checked);
					checked_thu = true;
				} else {
					thu.setImageResource(R.drawable.thursday);
					checked_thu = false;
				}
				break;
			case R.id.fri:
				if (!checked_fri) {
					fri.setImageResource(R.drawable.friday_checked);
					checked_fri = true;
				} else {
					fri.setImageResource(R.drawable.friday);
					checked_fri = false;
				}

				break;
			case R.id.sat:
				if (!checked_sat) {
					sat.setImageResource(R.drawable.saturday_checked);
					checked_sat = true;
				} else {
					sat.setImageResource(R.drawable.saturday);
					checked_sat = false;
				}
				break;
			case R.id.sun:
				if (!checked_sun) {
					sun.setImageResource(R.drawable.sunday_checked);
					checked_sun = true;
				} else {
					sun.setImageResource(R.drawable.sunday);
					checked_sun = false;
				}
				break;
			}
		}

	};

	Button.OnClickListener buttonListener = new Button.OnClickListener() {
		String before = "";
		int after = 0;

		@Override
		public void onClick(View arg0) {
			// TODO Auto-generated method stub
			switch (arg0.getId()) {
			case R.id.hour_plus:
				before = hour_t.getText().toString();
				if (before.equals("12"))
					hour_t.setText("01");
				else {
					after = Integer.parseInt(before) + 1;
					if (after < 10)
						hour_t.setText("0" + Integer.toString(after));
					else
						hour_t.setText(Integer.toString(after));
				}
				break;
			case R.id.hour_minus:
				before = hour_t.getText().toString();
				if (before.equals("01"))
					hour_t.setText("12");
				else {
					after = Integer.parseInt(before) - 1;
					if (after < 10)
						hour_t.setText("0" + Integer.toString(after));
					else
						hour_t.setText(Integer.toString(after));
				}
				break;
			case R.id.minute_plus:
				before = minute_t.getText().toString();
				if (before.equals("59"))
					minute_t.setText("00");
				else {
					after = Integer.parseInt(before) + 1;
					if (after < 10)
						minute_t.setText("0" + Integer.toString(after));
					else
						minute_t.setText(Integer.toString(after));
				}
				break;
			case R.id.minute_minus:
				before = minute_t.getText().toString();
				if (before.equals("00"))
					minute_t.setText("59");
				else {
					after = Integer.parseInt(before) - 1;
					if (after < 10)
						minute_t.setText("0" + Integer.toString(after));
					else
						minute_t.setText(Integer.toString(after));
				}
				break;
			case R.id.AM:
				before = am_pm_t.getText().toString();
				if (before.equals("AM"))
					am_pm_t.setText("PM");
				else
					am_pm_t.setText("AM");
			}
		}

	};

	TextView.OnClickListener musicTitleListener = new TextView.OnClickListener(){
		int index = 0;
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			new AlertDialog.Builder(Setting_alarm.this)
			.setTitle("음악 목록")
			.setAdapter(musicAdapter,
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(
								DialogInterface arg0, int arg1) {
							title = musicList.get(arg1);
							index = musicList.indexOf(title);
							music_id = getMusicID(index);
							musicTitle.setText(title);
						}
					}).create().show();
		}
		
	};
	
	
	RadioGroup.OnCheckedChangeListener soundListener = new RadioGroup.OnCheckedChangeListener() {
		int index = 0;
		@Override
		public void onCheckedChanged(RadioGroup group, int checkedId) {
			// TODO Auto-generated method stub
			if (group.getId() == R.id.radioGroup1) {
				switch (checkedId) {
				case R.id.radio0:
					new AlertDialog.Builder(Setting_alarm.this)
							.setTitle("음악 목록")
							.setAdapter(musicAdapter,
									new DialogInterface.OnClickListener() {
										@Override
										public void onClick(
												DialogInterface arg0, int arg1) {
											title = musicList.get(arg1);
											index = musicList.indexOf(title);
											music_id = getMusicID(index);
											musicTitle.setText(title);
										}
									}).create().show();
					break;
				}
			}
		}
	};

}
